<template>
  <view>
    <view class="content">
      <view class="list" v-if="addressList.length > 0">
        <view
          class="row"
          v-for="(row, index) in addressList"
          :key="index"
          @tap="select(row)"
        >
          <view class="left">
            <view class="head">
              {{ row.head }}
            </view>
          </view>
          <view class="center">
            <view class="name-tel">
              <view class="name">{{ row.name }}</view>
              <view class="tel">{{ row.phone }}</view>
              <view class="default" v-if="row.isDefault"> 默认 </view>
            </view>
            <view class="address"> {{ row.region }} {{ row.address }} </view>
          </view>
          <view class="right">
            <view class="icon bianji" @tap.stop="edit(row)"> </view>
            <view
              class="default-btn"
              @tap.stop="setDefault(row)"
              v-if="!row.isDefault"
            >
              设为默认
            </view>
          </view>
        </view>
      </view>
      <view class="list" v-else>
        <EmptyData
          main-text="暂无收货地址"
          sub-text="您还没有添加任何收货地址"
          :show-button="false"
        />
      </view>
    </view>
    <view class="add">
      <view class="btn" @tap="add">
        <view class="icon tianjia"></view>新增地址
      </view>
    </view>
  </view>
</template>
<script>
import {
  getAddressList,
  deleteAddress,
  updateAddress,
} from "@/common/api/address.js";
import { handleDefaultAddress } from "@/common/utils/address.js";
import EmptyData from "@/components/EmptyData.vue";

export default {
  components: {
    EmptyData,
  },
  data() {
    return {
      isSelect: false,
      addressList: [],
      customerId: "", // 客户ID，需要从登录信息中获取
    };
  },
  // Vue标准生命周期：组件实例创建后立即调用
  async created() {
    this.customerId = uni.getStorageSync("userInfo").id || "";

    // 加载地址列表
    this.loadAddressList();
  },

  // Vue标准生命周期：组件挂载到DOM后调用
  async mounted() {
    // 处理删除地址的返回
    this.handleDeletedAddress();

    // 处理保存地址的返回
    this.handleSavedAddress();

    // 检查是否是选择地址模式
    this.checkSelectMode();

    // 监听地址列表刷新事件
    uni.$on("refreshAddressList", this.loadAddressList);
  },
  methods: {
    // 检查是否是选择地址模式
    checkSelectMode() {
      // 在uni-app中，页面参数通过路由传递，这里需要其他方式获取
      // 可以通过全局状态或者其他方式来判断
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (currentPage.options && currentPage.options.type === "select") {
        this.isSelect = true;
      }
    },

    // 处理删除地址的返回
    handleDeletedAddress() {
      uni.getStorage({
        key: "delAddress",
        success: (e) => {
          if (e.data && e.data.hasOwnProperty("id")) {
            this.deleteAddressFromList(e.data.id);
          }
          uni.removeStorage({
            key: "delAddress",
          });
        },
      });
    },

    // 处理保存地址的返回
    handleSavedAddress() {
      uni.getStorage({
        key: "saveAddress",
        success: (e) => {
          if (e.data && e.data.hasOwnProperty("id")) {
            this.updateAddressInList(e.data);
          } else if (e.data) {
            this.addAddressToList(e.data);
          }
          uni.removeStorage({
            key: "saveAddress",
          });
        },
      });
    },
    // 加载地址列表
    loadAddressList() {
      if (!this.customerId) {
        return;
      }

      uni.showLoading({
        title: "加载中...",
      });

      getAddressList(this.customerId)
        .then((res) => {
          uni.hideLoading();
          if (res.data.ok) {
            // 转换API数据格式为页面显示格式
            this.addressList = res.data.data.map((item) => ({
              ...item,
              head: item.name.substr(0, 1),
            }));
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: "加载地址列表失败",
            icon: "none",
          });
        });
    },

    // 从列表中删除地址
    deleteAddressFromList(id) {
      const index = this.addressList.findIndex((item) => item.id === id);
      if (index > -1) {
        this.addressList.splice(index, 1);
      }
    },

    // 更新列表中的地址
    updateAddressInList(address) {
      const index = this.addressList.findIndex(
        (item) => item.id === address.id
      );
      if (index > -1) {
        this.addressList.splice(index, 1, address);
      }
    },

    // 添加地址到列表
    addAddressToList(address) {
      this.addressList.push(address);
    },

    edit(row) {
      uni.setStorage({
        key: "address",
        data: row,
        success() {
          uni.navigateTo({
            url: "edit/edit?type=edit&itemData=" + JSON.stringify(row),
          });
        },
      });
    },

    add() {
      uni.navigateTo({
        url: "edit/edit?type=add",
      });
    },

    select(row) {
      //是否需要返回地址(从订单确认页跳过来选收货地址)
      if (!this.isSelect) {
        return;
      }
      uni.setStorage({
        key: "selectAddress",
        data: row,
        success() {
          uni.navigateBack();
        },
      });
    },

    // 设置默认地址
    setDefault(row) {
      if (!this.customerId) {
        uni.showToast({
          title: "客户信息获取失败",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "设置默认地址",
        content: "确定要将此地址设为默认地址吗？",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: "设置中...",
            });
            updateAddress(row.id, {
              isDefault: true,
              customerId: this.customerId,
            })
              .then((response) => {
                uni.hideLoading();
                if (response.data.ok) {
                  uni.showToast({
                    title: "设置成功",
                    icon: "success",
                  });
                  this.loadAddressList();
                } else {
                  uni.showToast({
                    title: "设置失败",
                    icon: "none",
                  });
                }
              })
              .catch((err) => {
                uni.hideLoading();
              });
          }
        },
      });
    },
  },
  // Vue标准生命周期：组件销毁前调用
  beforeDestroy() {
    // 移除事件监听器
    uni.$off("refreshAddressList", this.loadAddressList);
  },
};
</script>

<style lang="scss">
view {
  display: flex;
}
// .icon {
//   &.bianji {
//     &:before{content:"\e61b";}
//   }
//   &.tianjia {
//     &:before{content:"\e81a";}
//   }
// }
.add {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 120upx;
  justify-content: center;
  align-items: center;
  .btn {
    box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
    width: 70%;
    height: 80upx;
    border-radius: 80upx;
    background-color: #f06c7a;
    color: #fff;
    justify-content: center;
    align-items: center;
    .icon {
      height: 80upx;
      color: #fff;
      font-size: 30upx;
      justify-content: center;
      align-items: center;
    }
    font-size: 30upx;
  }
}
.list {
  flex-wrap: wrap;
  .row {
    width: 96%;
    padding: 20upx 2%;
    .left {
      width: 90upx;
      flex-shrink: 0;
      align-items: center;
      .head {
        width: 70upx;
        height: 70upx;
        background: linear-gradient(to right, #ccc, #aaa);
        color: #fff;
        justify-content: center;
        align-items: center;
        border-radius: 60upx;
        font-size: 35upx;
      }
    }
    .center {
      width: 100%;
      flex-wrap: wrap;
      .name-tel {
        width: 100%;
        align-items: baseline;
        .name {
          font-size: 34upx;
        }
        .tel {
          margin-left: 30upx;
          font-size: 24upx;
          color: #777;
        }
        .default {
          font-size: 22upx;

          background-color: #f06c7a;
          color: #fff;
          padding: 0 18upx;
          border-radius: 24upx;
          margin-left: 20upx;
        }
      }
      .address {
        width: 100%;
        font-size: 24upx;
        align-items: baseline;
        color: #777;
      }
    }
    .right {
      flex-shrink: 0;
      align-items: center;
      margin-left: 20upx;
      .icon {
        justify-content: center;
        align-items: center;
        width: 80upx;
        height: 60upx;
        border-left: solid 1upx #aaa;
        font-size: 40upx;
        color: #777;
      }
      .default-btn {
        justify-content: center;
        align-items: center;
        width: 120upx;
        height: 60upx;
        border-left: solid 1upx #aaa;
        font-size: 24upx;
        color: #f06c7a;
        background-color: rgba(240, 108, 122, 0.1);
        border-radius: 8upx;
        margin-left: 10upx;
      }
    }
  }
}
</style>
